<template>
  <view class="page">
    <!-- 顶部渐变与标题 -->
    <view class="hero">
      <view class="dots"></view>
      <view class="hero-text">
        <text class="hero-title">退休规划小助手</text><br>
      </view>
    </view>

    <!-- 两个按钮卡片 -->
    <view class="cards">
      <view class="card" hover-class="card-hover" @click="goTo('/pages/calculator/index')">
        <image class="icon-img" src="/static/1.png" mode="widthFix"></image>
        <text class="card-title">退休计算器</text>
      </view>
      <view class="card" hover-class="card-hover" @click="goToWithLogin">
        <image class="icon-img" src="/static/2.png" mode="widthFix"></image>
        <text class="card-title">退休模拟器</text>
      </view>
    </view>

    <!-- 底部文案与配色 -->
    <view class="footer">
      <text class="footer-line">通过计算与模拟</text>
      <text class="footer-line">提前规划退休生活</text>
      <text class="footer-line">让未来更从容~</text>
    </view>
    
    <!-- 备案信息 -->
    <view class="beian">
      <text class="beian-text">国家工信部互联网ICP网站备案号：闽ICP备2024072909号-1</text>
      <text class="beian-text">公安联网全国互联网备案号：闽公网安备35030402009354号</text>
      <text class="beian-text">小程序备案号：闽ICP备2024072909号-2X</text>
    </view>
    
    <!-- 用户信息填写弹窗 -->
    <uni-popup ref="userInfoPopup" type="bottom" border-radius="20">
      <view class="popup-box">
        <view class="close-box" @click="onClosePopup">
          <image src="/static/close.png" mode="" class="close-icon"></image>
        </view>
        <view class="wx">
          <view class="wx-input">
            <view class="">头像</view>
            <button type="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar" class="btn">
              <image :src="avatarImg" class="wx-avatar"></image>
            </button>
          </view>
          <view class="wx-input">
            <view class="">昵称</view>
            <input type="nickname" class="usernickname" placeholder="请输入昵称" @blur="onNicknameBlur" />
          </view>
        </view>
        <view class="done" @click="submitUserInfo">
          确认
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import apiConfig from '@/config/api.js'

export default {
  data() {
    return {
      avatarImg: '/static/default-avatar.png', // 默认头像
      avatarBase64: '', // base64格式的头像
      wxname: '', // 用户昵称
      loginToken: '' // 临时存储登录token
    }
  },
  
  methods: {
    goTo(url) {
      uni.navigateTo({ url })
    },
    
    goToWithLogin() {
      uni.login({
        provider: "weixin",
        onlyAuthorize: true,
        success: (event) => {
          const {code} = event
          // 客户端成功获取授权临时票据（code）,向业务服务器发起登录请求。
          uni.request({
            url: `${apiConfig.baseUrl}/api/user/login`,
            data: {
              code: event.code
            },
            success: (res) => {
              // 获得token完成登录
              this.loginToken = res.data.data.token
              uni.setStorageSync('token', res.data.data.token)
              // 检查用户是否已有昵称和头像，如果没有则显示用户信息填写弹窗
              const user = res.data.data.user
              if (!user.nickname || !user.avatar) {
                // 用户信息不完整，显示用户信息填写弹窗
                this.$refs.userInfoPopup.open()
              } else {
                // 用户信息完整，直接跳转到模拟器页面
                uni.navigateTo({ url: '/pages/simulator/index' })
              }
            },
            fail: (err) => {
              console.error('登录请求失败', err)
              // 登录失败回首页并提示微信无感认证失败
              uni.showToast({
                title: '微信无感认证失败',
                icon: 'none',
                duration: 2000
              });
              // 延迟返回首页
              setTimeout(() => {
                uni.navigateBack()
              }, 2000);
            }
          })
        },
        fail: function (err) {
          // 登录授权失败
          // err.code是错误码
          console.error('微信登录授权失败', err)
          // 登录授权失败回首页并提示微信无感认证失败
          uni.showToast({
            title: '微信无感认证失败',
            icon: 'none',
            duration: 2000
          });
          // 延迟返回首页
          setTimeout(() => {
            uni.navigateBack()
          }, 2000);
        }
      })
    },
    
    onClosePopup() {
      this.$refs.userInfoPopup.close()
      // 关闭弹窗后直接跳转到模拟器页面
      uni.navigateTo({ url: '/pages/simulator/index' })
    },
    
    onChooseAvatar(e) {
      console.log("头像", e);
      this.avatarImg = e.detail.avatarUrl
      
      // 将选中的头像转换为base64格式
      this.convertUrlToBase64(e.detail.avatarUrl)
    },
    
    convertUrlToBase64(avatarUrl) {
      const fileSystemManager = uni.getFileSystemManager();
      fileSystemManager.readFile({
        filePath: avatarUrl,
        encoding: 'base64',
        success: (res) => {
          const base64Data = res.data;
          this.avatarBase64 = `data:image/jpeg;base64,${base64Data}`;
          console.log('Base64格式的头像数据:', this.avatarBase64);
        },
        fail: (error) => {
          console.error('读取文件失败:', error);
          // 如果转换失败，使用原始URL
          this.avatarBase64 = avatarUrl;
        }
      });
    },
    
    onNicknameBlur(e) {
      console.log("昵称", e);
      this.wxname = e.detail.value
    },
    
    submitUserInfo() {
      // 发送用户信息到服务器更新
      uni.request({
        url: `${apiConfig.baseUrl}/api/user/info`,
        method: 'POST',
        header: {
          'Authorization': `Bearer ${this.loginToken}`,
          'Content-Type': 'application/json'
        },
        data: {
          nickname: this.wxname,
          avatar: this.avatarBase64 || this.avatarImg
        },
        success: () => {
          // 更新成功后关闭弹窗并跳转到模拟器页面
          this.$refs.userInfoPopup.close()
          uni.navigateTo({ url: '/pages/simulator/index' })
        },
        fail: (err) => {
          console.error('更新用户信息失败', err)
          // 即使更新失败也关闭弹窗并跳转到模拟器页面
          this.$refs.userInfoPopup.close()
          uni.navigateTo({ url: '/pages/simulator/index' })
        }
      })
    }
  }
}
</script>

<style>
.page {
  background-color: #ffffff;
  min-height: 100vh; /* 使用视口高度确保占满屏幕 */
  display: flex;
  flex-direction: column;
}
.hero {
  flex: 1;
  height: 380rpx;
  background: linear-gradient(180deg, #E6F0FF 0%, #FFFFFF 100%);
  border-bottom-left-radius: 24rpx;
  border-bottom-right-radius: 24rpx;
  position: relative;
}
.hero-text {
  padding: 80rpx 40rpx 20rpx 40rpx;
  text-align: center;
}
.hero-title {
  font-weight: 800;
  font-size: 65rpx;
  color: #111827;
}
.hero-sub {
  margin-top: 28rpx;
  font-size: 32rpx;
  color: #4B5563;
}
.cards {
  display: flex;
  justify-content: space-between;
  padding: 30rpx 40rpx;
}
.card {
  width: 38%;
  background: #FFFFFF;
  border-radius: 36rpx;
  box-shadow: 0 12rpx 36rpx rgba(0,0,0,0.06);
  padding: 80rpx 36rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 380rpx;
}
.card-hover { opacity: 0.9; }
.icon-img {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 30rpx;
}
.card-title {
  font-weight: 700;
  font-size: 42rpx;
  color: #111827;
}
.footer {
  margin-top: 30rpx;
  padding: 0 40rpx 60rpx 40rpx;
  text-align: center;
  flex: 1;
}
.footer-line {
  color: #4B5563;
  font-size: 30rpx;
  display: block;
  line-height: 1.8;
}
.beian {
  background-color: #f8f9fa;
  padding: 20rpx 40rpx;
  text-align: center;
  border-top: 2rpx solid #e9ecef;
}
.beian-text {
  display: block;
  font-size: 20rpx;
  color: #6c757d;
  line-height: 1.6;
  margin-bottom: 8rpx;
}
.beian-text:last-child {
  margin-bottom: 0;
}

.wx-input {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.wx-input view {
  width: 60px;
  margin-right: 10px;
}

.btn {
  border: none;
  background: none;
  padding: 0;
}

.wx-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.usernickname {
  flex: 1;
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 8px;
}

.popup-box {
  padding: 20px;
  background: #fff;
}

.close-box {
  text-align: right;
  margin-bottom: 10px;
}

.close-icon {
  width: 24px;
  height: 24px;
}

.done {
  background-color: #007aff;
  color: white;
  text-align: center;
  padding: 12px;
  border-radius: 6px;
  margin-top: 20px;
}
</style>
